package com.dubito.github.data.http.interceptor

import android.util.Base64
import com.dubito.github.config.Settings
import com.dubito.github.constant.Constant
import com.dubito.github.ext.isLogin
import com.dubito.github.ext.otherwise
import com.dubito.github.ext.yes
import okhttp3.Interceptor
import okhttp3.Response

/**
 *@Author: liliang
 *@Date: 2020/8/4 8:48 PM
 *
 */
class AuthorizationInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // 下载请求不需要请求头
        return request.url.pathSegments.contains(Constant.DOWNLOAD).yes {
            chain.proceed(request)
        }.otherwise {
            chain.proceed(request.newBuilder().apply {
                when {
                    //登陆授权/退出接口
                    request.url.pathSegments.contains(Constant.AUTHORIZATIONS) -> {
                        val userCredentials =
                            "${Settings.Account.userName}:${Settings.Account.password}"
                        val auth = "basic ${Base64.encodeToString(
                            userCredentials.toByteArray(),
                            Base64.NO_WRAP
                        )}"
                        addHeader(Constant.AUTHORIZATION, auth)
                    }
                    //权限接口
                    isLogin() -> {
                        val auth = "Token ${Settings.Account.token}"
                        addHeader(Constant.AUTHORIZATION, auth)
                    }
                }
            }.build())
        }
    }
}